'use strict';

module.exports = app => {
  return class listService extends app.Service {
    /**
     * 获取列表信息
     * @param {string} dataTable - 查询的表
     * @param {object} select - 查询的字段
     * @param {number} page - 页码
     * @param {number} limit - 每页条数
     * @param {object} searchInfo - 查询条件 {searchType: string, searchData: string | object}
     * @return {object} - 验证结果 {count: number, data: object}
     */
    async searchList(dataTable, select, page, limit, sortInfo, searchInfo) {
      const { app, service } = this;
      const { searchType, searchData } = searchInfo;
      let [ count, data ] = [ 0, null ];
      const searchAllMethod = function () {
        for (const val of select) {
          this.orWhere(val, 'like', `%${searchData}%`);
        }
      }
      const searchItemMethod = function () {
        select.forEach(val => {
          if (searchData[val]) {
            const { data, type } = searchData[val];
            if (type) {
              if (type === 'search') {
                this.andWhere(val, 'like', `%${data}%`);
              } else if (type === 'date') {
                if (typeof data === 'object' && data.every(val => val !== null)) {
                  this.andWhereBetween(val, data);
                }
              }
            }
          }
        })
      }
      if (searchType === 'all') {
        count = await service.utils.getCount(dataTable, searchAllMethod);
        data = await service.utils.getListDetail(dataTable, select, page, limit, sortInfo, searchAllMethod);
      } else if (searchType === 'item') {
        count = await service.utils.getCount(dataTable, searchItemMethod);
        data = await service.utils.getListDetail(dataTable, select, page, limit, sortInfo, searchItemMethod);
      } else {
        count = await service.utils.getCount(dataTable);
        data = await service.utils.getListDetail(dataTable, select, page, limit, sortInfo);
      }
      return {
        count,
        data,
      };
    }
  };
};
